package syn;

/**
 * Remarks:
 * Class name :UnsafeBuyTicket
 * Date :2023/2/15 10:04
 * Author:杨俊源
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"张三").start();
        new Thread(buyTicket,"李四").start();
        new Thread(buyTicket,"黄牛").start();
    }
}

class BuyTicket implements Runnable{

    private int ticketNums = 10;
    boolean flag = true;

    public synchronized void buy(){
        if (ticketNums < 0){
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }

    @Override
    public void run() {
          while (flag){
              try {
                  Thread.sleep(100);
                  buy();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

          }
    }
}
